package com.xiaojianone.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xiaojianone.order.bean.Order;
import com.xiaojianone.order.properties.OrderProperties;
import com.xiaojianone.order.service.OrderService;
import jakarta.websocket.server.PathParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName  OrderController
 * Author  XiaojianOne
 * Date  2025/3/10 10:44
 * Version  8.0
 */

//@RequestMapping("api/order")
@Slf4j
//@RefreshScope
@RestController
public class OrderController {

    @Autowired
    private OrderProperties orderProperties;

    @Autowired
    private OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;


    @GetMapping("/config")
    public String config(){
        return "orderTimeout:"+ orderProperties.getTimeout() +
                ",orderAutoConfirm:" + orderProperties.getAutoConfirm() +
                ",dbUrl:" + orderProperties.getDbUrl();
    }


    @GetMapping("/create")
    public Order createOrder(@PathParam("productId") Long productId,
                             @PathParam("userId") Long userId){

        Order order = orderService.createOrder(productId, userId);

        return order;
    }


    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order",fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "productId",defaultValue = "888") Long productId,
                         @RequestParam(value = "userId",defaultValue = "1000") Long userId){

        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);

        return order;
    }


    /**
     * seckill兜底回调方法
     * @param productId
     * @param userId
     * @return
     */
    public Order seckillFallback(Long productId, Long userId, Throwable e){

        System.out.println("seckillFallback兜底回调方法执行了");

        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息:"+e.getClass());
        return order;
    }


    @GetMapping("/writeDb")
    public String writeDb(){
        return "write db";
    }

    @GetMapping("/readDb")
    public String readDb(){
        log.info("read db.....");
        return "read db";
    }
}
